package com.zwk.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zwk.base.entity.CommonResult;
import com.zwk.base.handler.GuLiException;
import com.zwk.edu.entity.Course;
import com.zwk.edu.entity.CourseDescription;
import com.zwk.edu.entity.Teacher;
import com.zwk.edu.entity.frontvo.CourseFrontVo;
import com.zwk.edu.entity.frontvo.CourseWebVo;
import com.zwk.edu.entity.vo.CourseInfoVo;
import com.zwk.edu.entity.vo.CoursePublishVo;
import com.zwk.edu.mapper.CourseDescriptionMapper;
import com.zwk.edu.mapper.CourseMapper;
import com.zwk.edu.service.ChapterService;
import com.zwk.edu.service.CourseDescriptionService;
import com.zwk.edu.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwk.edu.service.VideoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zwk
 * @since 2022-08-22
 */
@Service
@EnableTransactionManagement
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

//    @Autowired
//    private CourseDescriptionMapper courseDescriptionMapper;

    @Autowired
    private VideoService videoService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private CourseDescriptionService courseDescriptionService;

    // 添加课程基本信息
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        // 向课程表中添加数据
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo, course);
        int insert = courseMapper.insert(course);
        if (insert <= 0){
            throw new GuLiException(20001, "添加课程信息失败");
        }

        // 获取添加之后的课程id, 和课程简介建立一对一关系
        String id = course.getId();

        // 向课程简介表中添加数据
        CourseDescription courseDescription = new CourseDescription();
        BeanUtils.copyProperties(courseInfoVo, courseDescription);
        courseDescription.setId(id);
        boolean save = courseDescriptionService.save(courseDescription);
//        int insert1 = courseDescriptionMapper.insert(courseDescription);
        if (!save){
            throw new GuLiException(20001, "添加课程简介失败");
        }

        return id;
    }

    // 根据课程id查询课程信息
    @Override
    public CourseInfoVo getCourseById(String courseId) {
        // 获取课程基本信息
        Course course = courseMapper.selectById(courseId);
        // 获取课程简介
        CourseDescription courseDescription = courseDescriptionService.getById(courseId);

        // 封装数据
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(course, courseInfoVo);
        courseInfoVo.setDescription(courseDescription.getDescription());

        return courseInfoVo;
    }

    // 修改课程信息
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        // 修改课程表数据
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo, course);
        int update = courseMapper.updateById(course);
        if (update <= 0){
            throw new GuLiException(20001, "修改课程信息失败");
        }

        // 修改课程简介表数据
        CourseDescription courseDescription = new CourseDescription();
        BeanUtils.copyProperties(courseInfoVo, courseDescription);
        boolean update1 = courseDescriptionService.updateById(courseDescription);
        if (!update1){
            throw new GuLiException(20001, "修改课程简介失败");
        }
    }

    // 根据课程id查询所有课程相关信息
    @Override
    public CoursePublishVo publishCourseInfo(String id) {

        return courseMapper.getPublishCourseInfo(id);
    }

    // 删除课程
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public void removeCourse(String courseId) {

        // 删除小节内容
        videoService.removeByCourseId(courseId);
        // 删除章节内容
        chapterService.removeByCourseId(courseId);
        // 删除简介
        courseDescriptionService.removeById(courseId);
        // 删除课程
        int delete = courseMapper.deleteById(courseId);
        if (delete <= 0){
            throw new GuLiException(20001, "删除课程失败");
        }
    }

    // 条件查询带分页查询课程
    @Override
    public Map<String, Object> getCourseFrontList(Page<Course> page, CourseFrontVo courseFrontVo) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        // 查询已经发布的课程
        wrapper.eq("status", "Normal");
        // 判断条件是否为空
        if (courseFrontVo != null){
            // 判断一级分类是否为空
            if (ObjectUtils.isNotEmpty(courseFrontVo.getSubjectParentId())){
                wrapper.eq("subject_parent_id", courseFrontVo.getSubjectParentId());
                // 判断二级分类是否为空
                if (ObjectUtils.isNotEmpty(courseFrontVo.getSubjectId())){
                    wrapper.eq("subject_id", courseFrontVo.getSubjectId());
                }
            }
            // 判断是否按销量排序
            if (ObjectUtils.isNotEmpty(courseFrontVo.getBuyCountSort())){
                wrapper.orderByDesc("buy_count");
            }
            // 判断是否按时间排序
            if (ObjectUtils.isNotEmpty(courseFrontVo.getGmtCreateSort())){
                wrapper.orderByDesc("gmt_create");
            }
            // 判断是否按价格排序
            if (ObjectUtils.isNotEmpty(courseFrontVo.getPriceSort())){
                wrapper.orderByDesc("price");
            }
        }
        // 查询
        courseMapper.selectPage(page, wrapper);
        // 判断当前页是否非法
        if (page.getCurrent() > page.getPages()){
            page.setCurrent(page.getPages());
            courseMapper.selectPage(page, wrapper);
        }

        // 取出数据封装到map中
        Map<String, Object> map = new HashMap<>();
        List<Course> records = page.getRecords();
        long current = page.getCurrent();
        long pages = page.getPages();
        long size = page.getSize();
        long total = page.getTotal();
        boolean hasNext = page.hasNext(); // 上一页
        boolean hasPrevious = page.hasPrevious(); // 下一页
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    // 查询课程详情信息
    @Override
    public CourseWebVo getBaseCourseInfo(String id) {
        return courseMapper.selectBaseCourseInfo(id);
    }


}
